<?php
/**
 * 公开接口API
 * 家乡会等接口
 * 不需要验证用户身份token
 * @author David
 *
 */
namespace Api\Controller;

use Common\Controller\ApiController;
use Think\Page;

class HometownController extends ApiController{

    //我的同乡会（状态为：1-已通过、0-申请中、-1-被拒绝）
    public function getMyAssociation()
    {
        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $table='association';
        $cond=array('uid'=>$uid);
        $cond['status']=$_REQUEST['status'];
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','status desc,aid desc',$page->firstRow,$page->listRows);
        $club_list=array();
        foreach ($list as $key => $value) {
            $value['status_desc']=$this->transform_club_status($value['status']);
            $club_list[]=$this->communityMod->clubHandle($value);
        }

        $this->myApiPrint(200,$club_list,$extend_data);
    }

    //申请创建同乡会
    public function creategetAssociation()
    {
        
        $uid=$this->member_info ? $this->member_info['member_id'] : 0;
        if(!$uid){
            $this->myApiPrint('-2');
        }
        
        $city_id=$_REQUEST['city_id'] ? $_REQUEST['city_id'] : 0;
        $member_info=$this->comMod->detail('member',array('member_id'=>$uid),'member_name,member_id,school,student_photo,self_photo');
        $school_info=unserialize($member_info['school']);
        extract($school_info);
        unset($school_info);
        if($school_id==''){
            $this->myApiPrint(4010);
        }
        if(!$city_id){
            $this->myApiPrint(-3,'',array('msg'=>'未定位到城市信息'));
        }
        
        //图片上传
        if(!empty($_FILES['file']['size']))
        {
            $arc_img = 'aid_cover_'.$uid;
            $param = array('savePath'=>'association/aid_cover/','subName'=>'','files'=>$_FILES['file'],'saveName'=>$arc_img,'saveExt'=>'');
            $up_return = upload_one($param);
            if($up_return == 'error'){
                $this->myApiPrint(4005);
            }else{
                $info['img'] = $up_return;
            }
        }
        $member_info=$this->comMod->detail('member',array('member_id'=>$uid),'student_photo,self_photo');

        if(!empty($member_info['self_photo'])){
            $info['identification_photo'] = $member_info['self_photo'];
        }else{
            //上传个人照
            if(!empty($_FILES['identification_photo']['size']))
            {
                $arc_img = 'self_photo'.$info['uid'];
                $param = array('savePath'=>'member/self_photo/','subName'=>'','files'=>$_FILES['identification_photo'],'saveName'=>$arc_img,'saveExt'=>'');
                $up_return = upload_one($param);
                if($up_return == 'error'){
                    $this->myApiPrint(4005);
                }else{
                    $info['identification_photo'] = $up_return;
                }
            }
        }

        if(!empty($member_info['student_photo'])){
            $info['student_photo'] = $member_info['student_photo'];
        }else{
            //上传学生证照
            if(!empty($_FILES['student_photo']['size']))
            {
                $arc_img = 'student_photo'.$info['uid'];
                $param = array('savePath'=>'member/student_photo/','subName'=>'','files'=>$_FILES['student_photo'],'saveName'=>$arc_img,'saveExt'=>'');
                $up_return = upload_one($param);
                if($up_return == 'error'){
                    $this->myApiPrint(4005);
                }else{
                    $info['student_photo'] = $up_return;
                }
            }
        }

        //保存数据
        $info['school_id']=$school_id ? $school_id : 0;
        $info['city_id'] = $city_id;
        $info['uid'] = $uid;
        $info['title'] = $_REQUEST['name'];
        $info['des'] = $_REQUEST['desc'];
        $info['add_time'] = NOW_TIME;
        $info['status']=0;
        $result =  M("association")->add($info);
        if($result){

            //更新用户信息
            $memmber_data=array();
            if(!empty($info['student_photo'])){
                $memmber_data['student_photo']=$info['student_photo'];
            }
            if(!empty($info['identification_photo'])){
                $memmber_data['self_photo']=$info['identification_photo'];
            }
            if(!empty($memmber_data)){
                $this->comMod->saveData('member',array('member_id'=>$this->member_info['member_id']),$memmber_data); 
            }

            $this->myApiPrint(201);
        }else{
            $this->myApiPrint(-3);
        }
    }

    //同乡会主页显示的同乡会推荐的更多接口
    public function getRecommendAssociation()
    {
        $table='association';
        $cond['recommend']=1;
        $cond['status']=1;
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','aid desc',$page->firstRow,$page->listRows);
        foreach ($list as $key => $value) {
            $list[$key]=$this->comMod->bangdanHandle($value);
        }
        
        $this->myApiPrint('',$list,$extend_data);
    }


    //返回同乡会列表(本校同乡会、城市同乡会，搜索)
    public function getAssociationList()
    {
        $city_id=$_REQUEST['city_id'] ? $_REQUEST['city_id'] : 0;
        $condition['status']=1;  //审核通过
        $table='association';

        //搜索同乡会名称
        if(!empty($_REQUEST['name'])){
            $condition['title']=array('like','%'.$_REQUEST['name'].'%');  //社团类型
        }

        //获取用户学校信息
        $member_info=$this->comMod->getMemberInfoByID($this->member_info['member_id'],'member_name,member_id,school');
        extract(unserialize($member_info['school']));

        if($_REQUEST['level']=='1'){
            //本校同乡会
            $condition['school_id']=$school_id;
        }else{
            //本市同乡会
            $condition['city_id']=$city_id;
            if($school_id){
                $condition['school_id']=array('neq',$school_id);
            }
        }

        // $this->myApiPrint(-3,'',array('msg'=>'level id:'.$_REQUEST['level'].'----学校id：'.$school_id.'----'.'城市id：'.$city_id));
        
        //默认全部社团
        $order='count desc,aid desc';
        $page=$this->comMod->initPage($table,$condition,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows);
        $offset=$page->firstRow;
        $limit=$page->listRows; 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$condition,'*',$order,$offset,$limit);
        
        foreach ($list as $key => $value) {
            //今日发帖数
            $today_topic_count = $this->comMod->table(C('DB_PREFIX').'sectiontopic')->where(array('aid'=>$value['aid']))->count();
            //加入人数
            $members_count = $this->comMod->table(C('DB_PREFIX').'association_join')->where(array('aid'=>$value['aid'],'status'=>1))->count();

            $value['img']=$value['img'] ? PicPath.$value['img'] : DEFAULT_TOPIC_ICON;
            $value['today_topic_count']=$today_topic_count;
            $value['members_count']=$members_count;
            $list[$key]=$value;
        }

        $this->myApiPrint('',$list,$extend_data);
    }

    //家乡美，同乡互助，交流分享，方言(ok)
    public function getAssociation(){
        $condition=array();
        $extend_data=array();
        $type=$this->getSwitchType($_REQUEST['type']);
        $city_id=$_REQUEST['city_id'] ? $_REQUEST['city_id'] : 0;
        // $this->myApiPrint(-3,'',array('msg'=>$city_id));
        //用户学校信息
        $member_info=$this->comMod->getMemberInfoByID($this->member_info['member_id'],'member_name,member_id,school');
        extract(unserialize($member_info['school']));

        if($type=='17'){
            //本市同乡会
            $table="association";
            $order='aid desc';
            $condition['status']=1;
            $condition['city_id']=$city_id;
            if($school_id){
                $condition['school_id']=array('neq',$school_id);
            }
            $condition['status']=1;
            $list=$this->comMod->getList($table,$condition,'*',$order,0,5); 
        }else{
            //家乡美、方言、交流分享
            $table="sectiontopic";
            $order='latest_comment_time desc,article_id desc';
            $condition['ac_id']=$type; //文章分类id
            $condition['article_show']=1;
            $condition['city_id']=$city_id;
            $page=$this->comMod->initPage($table,$condition,$this->pageNum);
            $totalPages = ceil($page->totalRows / $page->listRows);
            $offset=$page->firstRow;
            $limit=$page->listRows; 
            $extend_data = $this->mobile_page($totalPages);
            
            $cur_page = intval($_REQUEST['curpage']);//当前页数
            if($condition['ac_id'] && $type!='29'){
                if($cur_page>1){
                    $offset=$offset-1;
                }else{
                    $limit=9;
                }
            }
            $list=$this->comMod->getList($table,$condition,'*',$order,$offset,$limit);
            // echo $this->comMod->getLastSql();
            // $this->myApiPrint(-3,'',array('msg'=>$this->comMod->getLastSql()));exit;

        }

        if($condition['ac_id'] && $type!='29'){
            //交流分享
            foreach($list as $key=>$value){
                $value2=$this->comMod->bangdanHandle($value);
                unset($value2['content']);
                if ($cur_page==1) {
                    if($key<3){
                        $specialData[0]['layoutType']='1';
                        $specialData[0]['itemData'][]=$value2;
                    }else{
                        $specialData[1]['layoutType']='2';
                        $specialData[1]['itemData'][]=$value2;
                    }
                }else{
                    $specialData[0]['layoutType']='2';
                    $specialData[0]['itemData'][]=$value2;
                }
                unset($value2);
            }
            $list= $specialData ? $specialData : array();
        }else{
            foreach($list as $key=>$value){
                    
                if(!$condition['ac_id']){

                    //今日发帖数
                    $today_topic_count = $this->comMod->table(C('DB_PREFIX').'sectiontopic')->where(array('aid'=>$value['aid']))->count();
                    //加入人数
                    $members_count = $this->comMod->table(C('DB_PREFIX').'association_join')->where(array('aid'=>$value['aid'],'status'=>1))->count();

                    $value['img']=$value['img'] ? PicPath.$value['img'] : DEFAULT_TOPIC_ICON;
                    $value['today_topic_count']=$today_topic_count;
                    $value['members_count']=$members_count;

                }else{
                    $value['article_time']=date("m-d H:i",$value['article_time']);
                }

                $value['pic']=$value['pic'] ? PicPath.$value['pic'] : '';

                $list[$key]=$value;

            }
        }

        //广告图
        $extend_data['actData']=array();
        $actData=M('adv_position')->where(array('ap_code'=>'banner_hometown_aid'))->select();
        foreach($actData as $key=>$value){
            $extend_data['actData'][] = $this->comMod->advMapping($value);
        }

        //本校同乡会
        if($school_id){
            $school_association_condition['school_id']=$school_id;
            $school_association_condition['status']=1;
            $school_associaton=M('association')->where($school_association_condition)->limit(0,5)->order('aid desc')->select();
        }

        foreach ($school_associaton as $key => $value) {
            
            //今日发帖数
            $today_topic_count = $this->comMod->table(C('DB_PREFIX').'sectiontopic')->where(array('aid'=>$value['aid']))->count();
            //加入人数
            $members_count = $this->comMod->table(C('DB_PREFIX').'association_join')->where(array('aid'=>$value['aid'],'status'=>1))->count();

            $value['img']=$value['img'] ? PicPath.$value['img'] : DEFAULT_TOPIC_ICON;
            $value['today_topic_count']=$today_topic_count;
            $value['members_count']=$members_count;

            $school_associaton[$key]=$value;
        }
        $extend_data['association']=$school_associaton ? $school_associaton : array();

        // foreach($associaton_recommend as $key=>$value){
        //     $value2['name']=$value['title'];
        //     $value2['icon']=$value['img']=$value['img'] ? PicPath.$value['img'] : '';
        //     $value2['aid']=$value['aid'];
        //     $extend_data['association'][] = $value2;
        // }

        $this->myApiPrint('',$list,$extend_data);
    }

    //同乡会详情（方言、交流、家乡美）
    public function getAssociationDetail(){
        $type=$this->getSwitchType($_REQUEST['type']);
        if($type=='17'){
            $this->myApiPrint(401); //不能传递aid
        }
        $uid=$this->member_info ? $this->member_info['member_id'] : 0;
        //同乡会描述
        $info=$this->hometownMod->getAssociationInfoByID($_REQUEST['aid']);
        $info['is_admin']=0;
        if($uid && $uid==$info['uid']){
            $info['is_admin']=1; //是管理员
        }
        //个人申请记录
        $association_join=$this->comMod->detail('association_join',array('aid'=>$_REQUEST['aid'],'uid'=>$uid),$fields='*');
        $join_status=$association_join ? $association_join['status'] : 3;
        switch ($join_status) {
            case 0:
                $info['is_join']='等待审核'; 
                break;
            case -1:
                $info['is_join']='申请加入'; //申请被拒
                break;
            case 1:
                $info['is_join']='已加入'; 
                break;
            case 2:
                $info['is_join']='申请加入'; //用户被踢出
                break;
            default:
                $info['is_join']='申请加入';  //用户未申请过
                break;
        }
        if($info['is_admin']){
            $info['is_join']='审核申请';
        }
        //列表
        $table='sectiontopic';
        $order='latest_comment_time desc,article_id desc';
        $cond['ac_id']=$type; //文章分类id
        // $cond['show']=1;
        $cond['aid']=$_REQUEST['aid']; //同乡会id
        $cond['article_show']=1;
        
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $offset=$page->firstRow;
        $limit=$page->listRows; 
        $extend_data = $this->mobile_page($totalPages);

        $cur_page = intval($_REQUEST['curpage']);//当前页数
        if($type!='29'){
            if($cur_page>1){
                $offset=$offset-1;
            }else{
                $limit=9;
            }
        }

        $list=$this->comMod->getList($table,$cond,'*',$order,$offset,$limit);

        if($type!='29'){
            //交流分享
            foreach($list as $key=>$value){
                $value2=$this->comMod->bangdanHandle($value);
                unset($value2['content']);

                if ($cur_page==1) {
                    if($key<3){
                        $specialData[0]['layoutType']='1';
                        $specialData[0]['itemData'][]=$value2;
                    }else{
                        $specialData[1]['layoutType']='2';
                        $specialData[1]['itemData'][]=$value2;
                    }
                }else{
                    $specialData[0]['layoutType']='2';
                    $specialData[0]['itemData'][]=$value2;

                }

                unset($value2);
            }
            $list= $specialData ? $specialData : array();
        }
        $extend_data['detail']=$info;
        $this->myApiPrint(200,$list,$extend_data);

    }

    //申请同乡会
    public function joinAssociation()
    {
        //检查是否存在申请
        $uid=$this->member_info ? $this->member_info['member_id'] : 0;
        if(!$uid){
            $this->myApiPrint('-2');
        }
        $join_record=$this->comMod->detail('association_join',array('aid'=>$_REQUEST['aid'],'uid'=>$uid),$fields='*');
        $join_status=$join_record ? $join_record['status'] : 3;
        if($join_status==1 || $join_status==0){
            $this->myApiPrint(4006); //已经是成员或申请中
        }
        // //图片或视频上传
        // if(!empty($_FILES['file']['size']))
        // {
        //     // $save_name=time().'_'.mt_rand();
        //     $param = array('savePath'=>'association/aid_join/','subName'=>$_REQUEST['aid'].'','files'=>$_FILES,'saveName'=>$_SERVER['REQUEST_TIME'],'saveExt'=>'');
        //     $up_return = multi_upload2($param); //视频或者照片都能传
        //     if($up_return == 'error'){
        //         $this->myApiPrint(4005); //上传失败
        //     }else{
        //         $info['video'] = $up_return[0] ? $up_return[0] : '';
        //         $info['sound'] = $up_return[1] ? $up_return[1] : '';
        //     }
            
        // }

        //图片上传
        if(!empty($_FILES['pic']['size']))
        {
            $arc_img = 'pic'.$uid;
            $param = array('savePath'=>'association/aid_join/','subName'=>'','files'=>$_FILES['pic'],'saveName'=>$arc_img,'saveExt'=>'');
            $up_return = upload_one($param,0);
            if($up_return == 'error'){
                $this->myApiPrint(4005);
            }else{
                $info['img'] = $up_return;
            }
        }

        //上传视频
        if(!empty($_FILES['video']['size']))
        {
            $arc_img = 'video'.$uid;
            $param = array('savePath'=>'association/aid_join/','subName'=>'','files'=>$_FILES['video'],'saveName'=>$arc_img,'saveExt'=>'');
            $up_return = upload_one($param,1);
            if($up_return == 'error'){
                $this->myApiPrint(4005);
            }else{
                $info['video'] = $up_return;
            }
        }

        //上传音频
        if(!empty($_FILES['sound']['size']))
        {
            $arc_img = 'sound'.$uid;
            $param = array('savePath'=>'association/aid_join/','subName'=>'','files'=>$_FILES['sound'],'saveName'=>$arc_img,'saveExt'=>'');
            $up_return = upload_one($param,2);
            if($up_return == 'error'){
                $this->myApiPrint(4005);
            }else{
                $info['sound'] = $up_return;
            }
        }
        //保存数据
        $association_info=$this->hometownMod->getAssociationInfoByID($_REQUEST['aid'],'title'); 
        $info['uid'] = $uid;
        $info['aid'] = $_REQUEST['aid'];
        $info['association_name'] = $association_info['title'];
        $info['add_time'] = NOW_TIME;
        if($join_status==3){
            //不存在申请记录
            $result =  M("association_join")->add($info);
        }else{
            //存在申请记录
            $cond['uid']=$uid;
            $cond['aid']=$_REQUEST['aid'];
            unset($info['uid']);
            unset($info['aid']);
            $info['status']=0; //修改为待审核状态
            $result =  M("association_join")->where($cond)->save($info);
        }
        
        if($result){
            $this->myApiPrint(200);
        }else{
            $this->myApiPrint(-3);
        }
    }

    //管理员同乡会申请列表
    public function getApplyList()
    {
        $condition=array();
        $table=C('DB_PREFIX')."association_join";
        $condition['status']=0;
        $condition['aid']=$_REQUEST['aid'];
        // $association_info=$this->hometownMod->getAssociationInfoByID($_REQUEST['aid'],'uid');

        // $member_info=$this->member_info;
        // if($association_info['uid']!=$member_info['member_id']){
        //     $this->myApiPrint(4007);
        // }
        
        $count = $this->comMod->table($table)->where($condition)->count();
        $page = new Page($count,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); //总页数
        $extend_data= $this->mobile_page($totalPages);
        $list=$this->comMod->table($table)->where($condition)->limit($page->firstRow,$page->listRows)->order($order)->select();
        ;
        foreach ($list as $key => $value) {
            $list[$key]=$this->hometownMod->associationApplyHandle($value);
        }
        $this->myApiPrint('',$list,$extend_data);
    }

    //同乡会申请详情
    public function getApplyDetail()
    {   
        $condition=array();
        $condition['status']=0;
        $condition['id']=$_REQUEST['id'];
        $detail=$this->comMod->detail('association_join',$condition,$fields='*');
        $extend_data=$this->hometownMod->associationApplyHandle($detail,'detail');
        if($extend_data){
            $this->myApiPrint('',$extend_data);
        }else{
            $this->myApiPrint(4008);
        }
    }

    //通过/拒绝申请审核
    public function allowApply()
    {
        $status=$_REQUEST['status']==-1 ? -1 : 1;
        $data=array('status'=>$status);
        $condition['id']=$_REQUEST['id'];
        $result=M("association_join")->where($condition)->save($data);
        if($result){
            $this->myApiPrint(200);
        }else{
            $this->myApiPrint(-3);
        }
    }

    //公公共方法

    public function getSwitchType($type){

        switch ($type)
        {
            case 'aid': //同乡会列表
                $type='17';
                break;
            case 'dialet': //方言
                $type='28';
                break;
            case 'communication': //交流
                $type='29';
                break;
            case 'home': //家乡美
                $type='27';
                break;
        }
        return $type;
    }
    
    //未用
    function checkHasJoinAssociation(){
        $step=1;
        $join_record=$this->comMod->table(C('DB_PREFIX')."association_join")->where(array('aid'=>$_REQUEST['aid'],'uid'=>$_REQUEST['uid']))->find();
        if(empty($join_record)){
            if($join_record['video']==''){
                $step=1; //返回第一步更新视频或照片
            }else{
                $step=2;
            }
        }
        return false;
    }


}